import React from 'react';
import { Icon  } from 'antd';
import './style/index.less';

export default class FieldSet extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      type: props.expanded === false ? 'plus' : 'minus',
    };
  }
  componentWillReceiveProps(nextProps){
    if (nextProps.expanded !== this.props.expanded) {
      this.setState({
        type: nextProps.expanded === false ? 'plus' : 'minus',
      });
    }
  }
  _iconClick = () => {
    const { showArray, onToggle } = this.props;
    if (showArray !== false) {
        if (this.state.type === 'minus') {
        this.setState({
          type: 'plus',
        });
        onToggle && onToggle(false);
      } else {
        this.setState({
          type: 'minus',
        });
        onToggle && onToggle(true);
      }
    }
  };
  _renderField = (children,readOnly,reading) => {
    /* eslint-disable */
    if(this.flag && children){
      if(Object.prototype.toString.call(children).slice(8,-1) === 'Object'){
        return React.cloneElement(children, { readOnly, reading, ...children.props});
      }
      return children.map((item,index) => React.cloneElement(item,{readOnly, reading,key:index, ...item.props}));
    }
    return null;
  };
  render() {
    const { children, readonly, reading, style, className, legend, prefix = 'data-mocker', showArrow = true } = this.props;
    const { type } = this.state;
    let tempClassName = `${prefix}-field-set`;
    if (type === 'minus') {
      this.flag = true;
      tempClassName = `${tempClassName}-expanded`;
    } else {
      tempClassName = `${tempClassName}-unexpanded`;
    }
    return (
      <fieldset
        className={`${prefix}-field-set ${className || ''} ${tempClassName}`}
        style={{
          ...style,
          margin:'5px',
          padding:'5px',
        }}
      >
        {
          showArrow ?
            (<legend onClick={this._iconClick}>
              <div className={`${prefix}-field-set-legend`}>
                <Icon type={this.state.type} className={`${prefix}-field-set-legend-icon`}/>
                <div className={`${prefix}-field-set-legend-content`}>{legend}</div>
              </div>
            </legend>)
            :
            (<legend>
              <div className={`${prefix}-field-set-legend`}>
                <div className={`${prefix}-field-set-legend-content`}>{legend}</div>
              </div>
            </legend>)
        }
        <div style={{display:type !== 'minus' ? 'none' : ''}}>
          {this._renderField(children,readonly,reading)}
        </div>
      </fieldset>
    );
  }
}
